package com.lancoo.znbkxx.teacher.ui.fragment

import android.annotation.SuppressLint
import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.AnimationDrawable
import android.graphics.drawable.ColorDrawable
import android.media.MediaPlayer
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.core.os.bundleOf
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.chad.library.adapter.base.BaseQuickAdapter
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.AnswerListAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.databinding.DialogClassicalBinding
import com.lancoo.znbkxx.teacher.model.data.Classical
import com.lancoo.znbkxx.teacher.utils.ToastUtils
import com.lancoo.znbkxx.teacher.viewmodel.HardSolutionViewModel
import com.lancoo.znbkxx.teacher.aibkTestCoach.auidoPlayer.AudioTracker
import com.luck.picture.lib.tools.ScreenUtils
import kotlinx.android.synthetic.main.dialog_classical.view.*


/**
 * @author : wealive
 * @date   : 2020/3/16 11:36
 * @desc   :
 */
class ClassicalDialog(val data: MutableList<Classical>,
        val onItemClickListener: BaseQuickAdapter.OnItemClickListener,
        val onClickListener: ClassicalFragment.OnClickClassicalListener
) : AppCompatDialogFragment(), AnswerListAdapter.OnAudioClickListener,
        MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener {
    private var audioTracker: AudioTracker? = null
    lateinit var ivAudio: ImageView
    lateinit var viewModel: HardSolutionViewModel

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        viewModel = ViewModelProvider(this).get(HardSolutionViewModel::class.java)
        lifecycle.addObserver(viewModel)
        val binding = DataBindingUtil.inflate<DialogClassicalBinding>(
                inflater,
                R.layout.dialog_classical,
                container,
                false
        )
        binding.lifecycleOwner = this
        dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        return binding.root
    }

    @SuppressLint("SetTextI18n")
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val view = requireActivity().layoutInflater.inflate(R.layout.dialog_classical, null)
        view.iv_close.setOnClickListener { this.dismiss() }
        view.vp.apply {
            offscreenPageLimit = 2
            adapter = object : FragmentStateAdapter(childFragmentManager, lifecycle) {
                override fun getItemCount(): Int {
                    return data.size
                }

                override fun createFragment(position: Int): Fragment {
                    return ClassicalFragment(onClickListener, this@ClassicalDialog).apply {
                        arguments =
                                bundleOf(Pair("position", position), Pair("item", data[position]),
                                        Pair("dialogTag", this@ClassicalDialog.tag))
                    }
                }
            }
            registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    view.tv_num.text = "${position + 1}/${data.size}"
                }
            })
            setPageTransformer(PageTranformWithAlpha())
        }
        if (tag == "add") {
            view.tv_num.visibility = View.VISIBLE
            view.tv_num.text = "1/${data.size}"
        } else {
            view.tv_num.visibility = View.GONE
        }
        return AlertDialog.Builder(requireContext()).setView(view).create()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        viewModel.audioPath.observe(this, Observer {
            audioTracker!!.setMFilePath(it)
            audioTracker!!.start()
        })
        super.onViewCreated(view, savedInstanceState)
    }

    override fun onResume() {
        super.onResume()
        audioTracker?.pause()
        dialog?.setCancelable(false)
        dialog?.setCanceledOnTouchOutside(false)
        val param = this.dialog?.window?.attributes
        param?.width = ScreenUtils.getScreenWidth(context)
        param?.height = WindowManager.LayoutParams.WRAP_CONTENT
        dialog?.window?.attributes = param
    }

    fun getClassicalInfoList(): MutableList<Classical> {
        return data
    }

    override fun success(view: ImageView, index: Int, position: Int) {
        ivAudio = view
        val path = data[position].AnswerList[0].AudioPath
//            data[position].AnswerList[0].SubChildList[0].SubChildItem[0].AudioPath
        playAudio(path)
    }

    private fun playAudio(path: String) {
        audioTracker = AudioTracker()
        lifecycle.addObserver(audioTracker!!)
        audioTracker!!.createAudioTrack()
        audioTracker!!.setImageView(ivAudio)
        val url = Ext.OBSINFO?.ServerWithBucket + path
        audioTracker!!.setPlayListener(object : AudioTracker.PlayListener {
            override fun playStart() {

            }

            override fun playPrepare() {
                requireActivity().runOnUiThread { MyToast.showToast("音频正在加载中...") }
            }

            override fun playFinish() {
            }

        })
        viewModel.downLoadAudio(url, url.substring(url.lastIndexOf("/") + 1))
    }

    override fun onPrepared(mp: MediaPlayer?) {
        mp?.start()
        ivAudio.setImageResource(R.drawable.anim_laba)
        val drawable = ivAudio.drawable as? AnimationDrawable
        drawable?.start()
    }

    override fun onCompletion(mp: MediaPlayer?) {
        val drawable = ivAudio.drawable as? AnimationDrawable
        if (drawable != null && drawable.isRunning) {
            drawable.stop()
            drawable.selectDrawable(0)
            ivAudio.clearAnimation()
            ivAudio.setImageResource(R.mipmap.laba3)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        audioTracker?.release()
        audioTracker = null
    }

}